package private

import (
	"strconv"

	"github.com/sirupsen/logrus"
	"github.com/xuelang-group/sh-solver-scheduler/internal/controller"
	"github.com/xuelang-group/sh-solver-scheduler/internal/infra"
	"github.com/xuelang-group/sh-solver-scheduler/pkg/server"

	"github.com/gin-gonic/gin"
)

type task struct {
}

func NewInternalTaskController() controller.Controller {
	return &task{}
}

func (c *task) Name() string {
	return "internalController"
}

func (p *task) RegisterRoute(api *gin.RouterGroup) {
	// 创建任务(执行求解器)
	api.POST("/task/status/update", p.updateTaskStatus)
}

type ArgsReq struct {
	NetworkId string `json:"networkId,omitempty"` // appId
	NodeId    string `json:"nodeId,omitempty"`
	Status    string `json:"status,omitempty"` // running success failed
	Expire    int    `json:"expire,omitempty"`
}

type ReqUpdateTaskStatus struct {
	Method string  `json:"method"`
	Args   ArgsReq `json:"args"`
	Msg    string  `json:"msg,omitempty"` // log msg
}

func (c *task) updateTaskStatus(context *gin.Context) {
	body := ReqUpdateTaskStatus{}

	if err := context.BindJSON(&body); err != nil {
		server.ResponseFailed(context, 0, err)
		return
	}

	logrus.Info("update task status...")
	logrus.Infof("body: %+v", body)

	// 更新状态
	taskID, _ := strconv.Atoi(body.Args.NetworkId)
	taskStatus := body.Args.Status
	infra.UpdateSolverTaskStatus(taskID, taskStatus)

	// 更新日志
	if body.Msg != "" {
		infra.UpdateSolverTaskLogMsg(taskID, body.Msg, "override")
	}

	switch taskStatus {
	case "success", "failed":
		// TODO: 命名空间可以通过传递并传回来task pod
		// if err := k8s.Client().DeletePod("sh-dc", strconv.Itoa(taskID)); err != nil {
		// 	logrus.Errorf("delete task(id: %v) pod failed, err: %v", taskID, err)
		// }
	}

	server.ResponseSuccess(context, "")
}
